<?php

final class Image
{
    static public function resize($path, $width = 200, $height = 150)
    {
        $info = getimagesize($path);
        $ratio = min($width / $info[0], $height / $info[1]);
        if ($ratio != 1) {
            $dir = Path::directory($path);
            if ($dir) {
                $fle = Path::fileName($path);
                $ext = Path::extension($path);
                $thumb = "{$dir}/{$fle}-{$width}x{$height}.{$ext}";
                $affine = [$ratio, 0, 0, $ratio, 0, 0];
                switch ($info[2]) {
                    case 2:
                        $image = imagecreatefromjpeg($path);
                        if ($image) {
                            $clone = imageaffine($image, $affine);
                        }
                        break;
                    case 3:
                        $image = imagecreatefrompng($path);
                        if ($image) {
                            $clone = imageaffine($image, $affine);
                        }
                        break;
                }
                if ($image) {
                    imagedestroy($image);
                }
                if ($clone) {
                    imagepng($clone, $thumb);
                    imagedestroy($clone);
                    return $thumb;
                }
            }
        }
        return $path;
    }
}